﻿﻿// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using Microsoft.ServiceBus.Messaging;
using System;

namespace Nardax.Azure.ServiceBus
{
    public class SubscriptionClientWrapper : IMessageReceiver
    {
        private readonly SubscriptionClient _subscriptionClient;
        private bool _isReceiving;

        public SubscriptionClientWrapper(string connectionString, string topicPath, string subscriptionName)
        {
            _subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topicPath, subscriptionName);
        }

        public IAsyncResult BeginReceive(TimeSpan serverWaitTime, AsyncCallback callback, object state)
        {
            if (_isReceiving)
            {
                return null;
            }

            _isReceiving = true;

            return _subscriptionClient.BeginReceive(serverWaitTime, callback, state);
        }

        public BrokeredMessage EndReceive(IAsyncResult result)
        {
            try
            {
                var message = _subscriptionClient.EndReceive(result);
                return message;
            }
            finally
            {
                _isReceiving = false;
            }
        }

        public void Close()
        {
            _subscriptionClient.Close();
        }

        public int PrefetchCount
        {
            get { return _subscriptionClient.PrefetchCount; }
            set { _subscriptionClient.PrefetchCount = value; }
        }

        public bool IsEmpty { get; set; }

        public string Namespace
        {
            get { return _subscriptionClient.MessagingFactory.Address.DnsSafeHost; }
        }

        public string Path
        {
            get { return string.Format("{0}/{1}", _subscriptionClient.TopicPath, _subscriptionClient.Name); }
        }
    }
}
